import LNotification from "./LNotification";

let messageInstance = undefined;

function getMessageInstance(args, callback) {
  const { appContext } = args;
  LNotification.newInstance({
    appContext,
  },
  (instance) => {
    if (messageInstance) {
      callback(messageInstance);
      return;
    }
    messageInstance = instance;
    callback(instance);
  });
}

function notice(args) {
  getMessageInstance(args, (instance) => {
    instance.notice({
      content: args.content,
      type: args.type,
    });
  });
}

let api = {
  open: notice,
};

function attachTypeApi(originalApi, type) {
  originalApi[type] = (
    content,
    duration,
    onClose,
  ) => {
    if (typeof duration === "function") {
      onClose = duration;
      duration = undefined;
    }
    return originalApi.open({ content, duration, type, onClose });
  };
}

["success", "error", "warning"].forEach(type => {
  attachTypeApi(api, type);
});

export default api;

window.message = api;